package com.xp.pgoj.service;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Set;

/**
 * @author <a href=""https://github.com/Fzs0>逢左使</a>
 * @create 2024/10/24 15:01
 * @Description:
 */
@Service
public class RankService {

    @Resource
    private RedisTemplate<String, String> redisTemplate;

    private static final String RANK_KEY_PREFIX = "daily_rank:";
    private static final String COMPLETED_QUESTIONS_KEY_PREFIX = "completed_questions:";

    private String getTodayKey() {
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyyMMdd");
        return dateFormat.format(new Date());
    }

    public void updateRank(String userId, String questionId) {
        if (StringUtils.isEmpty(userId) || StringUtils.isEmpty(questionId)) {
            return;
        }
        String todayKey = getTodayKey();
        String rankKey = RANK_KEY_PREFIX + todayKey;
        String completedQuestionsKey = COMPLETED_QUESTIONS_KEY_PREFIX + todayKey + ":" + userId;

        // 检查用户是否已经完成该题目
        if (!redisTemplate.opsForSet().isMember(completedQuestionsKey, questionId)) {
            // 更新排行榜分数
            redisTemplate.opsForZSet().incrementScore(rankKey, userId, 1);
            // 记录用户已完成的题目
            redisTemplate.opsForSet().add(completedQuestionsKey, questionId);
        }
    }

    public Set<ZSetOperations.TypedTuple<String>> getTopNRank(int n) {
        String rankKey = RANK_KEY_PREFIX + getTodayKey();
        return redisTemplate.opsForZSet().reverseRangeWithScores(rankKey, 0, n - 1);
    }

}
